package com.aiyige.page.user;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.Router;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.glide.GlideBannerImageLoader;
import com.aiyige.im.SessionHelper;
import com.aiyige.model.User;
import com.aiyige.model.sns.Follow;
import com.aiyige.page.user.adapter.UserViewPagerAdapter;
import com.aiyige.share.ShareDialog;
import com.aiyige.track.annotation.Track;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.banner.BannerAdapter;
import com.aiyige.utils.dialog.LoadingDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.flyco.tablayout.SlidingTabLayout;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@Track("动态展示")
@Route(path = ARouterConfig.UserPage)
public class UserPage extends BaseActivity {
    public static final String SHARE_URL = "http://www.aiyige.com/userpage/%s";

    @BindView(R.id.titleUserNameTv)
    TextView titleUserNameTv;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.avatarIv)
    ImageView avatarIv;
    @BindView(R.id.userNameTv)
    TextView userNameTv;
    @BindView(R.id.followNumTv)
    TextView followNumTv;
    @BindView(R.id.fanNumTv)
    TextView fanNumTv;
    @BindView(R.id.introductionTv)
    TextView introductionTv;
    @BindView(R.id.introductionIv)
    ImageView introductionIv;
    @BindView(R.id.backBtn)
    ImageView backBtn;
    @BindView(R.id.tabLayout)
    SlidingTabLayout tabLayout;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.introductionLayout)
    View introductionLayout;

    @Autowired
    String userId;
    @BindView(R.id.sexIv)
    ImageView sexIv;
    List<BannerAdapter.Data> bannerAdapterDataList = new LinkedList<>();
    User user;
    @BindView(R.id.verifyIv)
    ImageView verifyIv;
    @BindView(R.id.userNameLayout)
    RelativeLayout userNameLayout;
    @BindView(R.id.followNumLayout)
    LinearLayout followNumLayout;
    @BindView(R.id.fanNumLayout)
    LinearLayout fanNumLayout;
    @BindView(R.id.followedLayout)
    LinearLayout followedLayout;
    @BindView(R.id.followLayout)
    LinearLayout followLayout;
    @BindView(R.id.editLayout)
    LinearLayout editLayout;
    @BindView(R.id.appbar)
    LinearLayout appbar;
    @BindView(R.id.shareBtn)
    ImageView shareBtn;
    @BindView(R.id.chatBtn)
    ImageView chatBtn;
    @BindView(R.id.mutualfollowedLayout)
    LinearLayout mutualfollowedLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_user);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        if (TextUtils.isEmpty(userId)) {
            ToastX.show(R.string.user_info_error);
            finish();
            return;
        }
        initBanner();
        viewPager.setAdapter(new UserViewPagerAdapter(getSupportFragmentManager(), userId));
        tabLayout.setViewPager(viewPager);
        if (checkSelf()) {
            showEditLayout();
            chatBtn.setVisibility(View.INVISIBLE);
        } else {
            chatBtn.setVisibility(View.VISIBLE);
            editLayout.setVisibility(View.INVISIBLE);
            followLayout.setVisibility(View.INVISIBLE);
            followedLayout.setVisibility(View.INVISIBLE);
            mutualfollowedLayout.setVisibility(View.INVISIBLE);
        }
    }

    public static void start(String userId) {
        ARouter.getInstance().build(ARouterConfig.UserPage).withString("userId", userId).navigation();
    }

    public static void start(long userId) {
        ARouter.getInstance().build(ARouterConfig.UserPage).withString("userId", userId + "").navigation();
    }

    private boolean checkSelf() {
        if (TextUtils.isEmpty(userId)) {
            return false;
        } else {
            return userId.equals(AccountUtil.getCurrentUser().getId());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestData();
    }


    public void requestData() {
        ApiManager.getService()
                .userCenterUsers(userId)
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            if (response.code() != ResponseCode.OK) {
                                throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                            }
                            String json = RetrofitUtil.getResponseBodyAsString(response);
                            user = JSON.parseObject(json, User.class);
                            user = new User(user);
                            Glide.with(UserPage.this)
                                    .load(user.getAvatar())
                                    .apply(RequestOptions.placeholderOf(R.drawable.default_head))
                                    .apply(RequestOptions.circleCropTransform())
                                    .into(avatarIv);
                            switch (user.getMoreBackup().getSex()) {
                                case User.GENDER_FEMALE:
                                    sexIv.setVisibility(View.VISIBLE);
                                    sexIv.setImageResource(R.drawable.personal_girl);
                                    break;
                                case User.GENDER_MALE:
                                    sexIv.setVisibility(View.VISIBLE);
                                    sexIv.setImageResource(R.drawable.personal_boy);
                                    break;
                                default:
                                    sexIv.setVisibility(View.INVISIBLE);
                                    break;
                            }
                            titleUserNameTv.setText(user.getAccount());
                            userNameTv.setText(user.getAccount());
                            followNumTv.setText(StringUtils.formatNum(user.getStatisticsBackup().getFollowCount()));
                            fanNumTv.setText(StringUtils.formatNum(user.getStatisticsBackup().getFollowersCount()));
                            if (TextUtils.isEmpty(user.getMoreBackup().getIntroduce())) {
                                introductionTv.setText(R.string.no_introduciton);
                                introductionIv.setVisibility(View.INVISIBLE);
                                introductionLayout.setEnabled(false);
                            } else {
                                introductionTv.setText(user.getMoreBackup().getIntroduce());
                                introductionIv.setVisibility(View.VISIBLE);
                                introductionLayout.setEnabled(true);
                            }
                            if (checkSelf()) {
                                showEditLayout();
                            } else if (!TextUtils.isEmpty(user.getMineBackup().getUserFollowId()) && user.getMineBackup().isMutualFollower()) {
                                showMutualFollowedLayout();
                            } else if (!TextUtils.isEmpty(user.getMineBackup().getUserFollowId())) {
                                showFollowedLayout();
                            } else {
                                showFollowLayout();
                            }

                            if (!ListUtil.isEmpty(user.getSlideBackup())) {
                                bannerAdapterDataList.clear();
                                for (User.SlideImage slideImage : user.getSlideBackup()) {
                                    BannerAdapter.Data bannerAdapterData = new BannerAdapter.Data();
                                    bannerAdapterData.setId(slideImage.getId());
                                    bannerAdapterData.setTitle(slideImage.getTitle());
                                    bannerAdapterData.setUrl(slideImage.getUrl());
                                    bannerAdapterData.setLink(slideImage.getRouter());
                                    bannerAdapterData.setRouter(slideImage.getRouter());
                                    bannerAdapterData.setOwner(slideImage.getUserId());
                                    bannerAdapterDataList.add(bannerAdapterData);
                                }
                                banner.update(bannerAdapterDataList);
                            } else {
                                banner.update(new LinkedList<>());
                            }
                        } catch (Exception e) {
                            onFailure(call, e);
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        ToastX.show(t.getMessage());
                    }
                });
    }

    public void initBanner() {
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setImageLoader(new GlideBannerImageLoader());
        banner.setBannerAnimation(Transformer.Default);
        banner.setDelayTime(3000);
        banner.isAutoPlay(true);
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Router.start(bannerAdapterDataList.get(position).getLink());
            }
        });
        banner.start();
    }


    @OnClick({R.id.chatBtn, R.id.mutualfollowedLayout, R.id.followedLayout, R.id.followLayout, R.id.editLayout, R.id.shareBtn, R.id.followNumLayout, R.id.fanNumLayout, R.id.introductionLayout, R.id.backBtn, R.id.avatarIv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.chatBtn:
                try {
                    SessionHelper.startP2PSession(this, user.getUserAccidPassword().getAccid());
                } catch (Exception e) {
                }
                break;
            case R.id.shareBtn:
                if (user != null && !TextUtils.isEmpty(user.getMoreBackup().getWebUrl())) {
                    ShareDialog.newInstance(this).shareUser(user);
                } else {
                    //ToastX.show(R.string.invalid_share_url);
                }
                break;
            case R.id.followNumLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.FollowPage)
                        .withString("userId", userId)
                        .navigation();
                break;
            case R.id.fanNumLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.FansPage)
                        .withString("userId", userId)
                        .navigation();
                break;
            case R.id.introductionLayout:
                ARouter.getInstance().build(ARouterConfig.UserIntroductionPage)
                        .withString("introduction", introductionTv.getText().toString())
                        .navigation();
                break;
            case R.id.backBtn:
                finish();
                break;
            case R.id.editLayout:
                if (!AccountUtil.isLogin()) {
                    ARouter.getInstance()
                            .build(ARouterConfig.LoginPage)
                            .navigation(this);
                } else {
                    ARouter.getInstance().build(ARouterConfig.EditUserIntroductionBannerPage).navigation();
                }
                break;
            case R.id.mutualfollowedLayout:
            case R.id.followedLayout:
                if (!AccountUtil.isLogin()) {
                    ARouter.getInstance()
                            .build(ARouterConfig.LoginPage)
                            .navigation(this);
                } else {
                    new DeleteFollowTask().execute();
                }
                break;
            case R.id.followLayout:
                if (!AccountUtil.isLogin()) {
                    ARouter.getInstance()
                            .build(ARouterConfig.LoginPage)
                            .navigation(this);
                } else {
                    new AddFollowTask().execute();
                }
                break;


            case R.id.avatarIv:
                startPhotoPage();
                break;
        }
    }

    private void startPhotoPage() {
        if (user == null) {
            return;
        }
        ARouter.getInstance()
                .build(ARouterConfig.PhotoViewPage)
                .withString("photoUrl", user.getAvatar())
                .navigation();
    }


    public class DeleteFollowTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(UserPage.this)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .deleteFollow(user.getMineBackup().getUserFollowId())
                        .execute();
                if (response.code() != ResponseCode.NO_CONTENT) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                user.getMineBackup().setUserFollowId("");
                showFollowLayout();
            }
        }
    }

    public void showEditLayout() {
        editLayout.setVisibility(View.VISIBLE);
        followLayout.setVisibility(View.GONE);
        followedLayout.setVisibility(View.GONE);
        mutualfollowedLayout.setVisibility(View.GONE);
    }

    public void showFollowLayout() {
        editLayout.setVisibility(View.GONE);
        followLayout.setVisibility(View.VISIBLE);
        followedLayout.setVisibility(View.GONE);
        mutualfollowedLayout.setVisibility(View.GONE);
    }

    public void showFollowedLayout() {
        editLayout.setVisibility(View.GONE);
        followLayout.setVisibility(View.GONE);
        followedLayout.setVisibility(View.VISIBLE);
        mutualfollowedLayout.setVisibility(View.GONE);
    }

    public void showMutualFollowedLayout() {
        editLayout.setVisibility(View.GONE);
        followLayout.setVisibility(View.GONE);
        followedLayout.setVisibility(View.GONE);
        mutualfollowedLayout.setVisibility(View.VISIBLE);
    }


    public class AddFollowTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(UserPage.this)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().addFollow(Follow.newBuilder()
                        .beFollowedId(user.getId())
                        .followerId(AccountUtil.getCurrentUser().getId())
                        .build())
                        .execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                Follow follow = JSON.parseObject(json, Follow.class);
                if (follow == null) {
                    throw new Exception("添加关注失败");
                }
                return new Follow(follow);
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                Follow follow = (Follow) o;
                user.getMineBackup().setUserFollowId(follow.getId());
                user.getMineBackup().setMutualFollower(follow.getMutualFollower());
                if (follow.getMutualFollower()) {
                    showMutualFollowedLayout();
                } else {
                    showFollowedLayout();
                }
                ToastX.show(R.string.add_follow_success);
            }
        }
    }

}
